package com.tsinghuabigdata.edu.ddmath.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.SetHeadImage;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.activity.TestRoomActivity;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.SelectQuestionsActivity;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.dialog.SelectTimeDialog;
import com.tsinghuabigdata.edu.ddmath.dialog.TutorDialog;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.TutorModel;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.adapter.OnlineTutoringAdapter;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.bean.ApplyTutor;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.bean.OnlineTutoring;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.bean.TutorApplied;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.bean.TutorState;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.bean.TutorTurn;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.util.DateUtils;
import com.tsinghuabigdata.edu.ddmath.util.GlobalData;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;
import com.tsinghuabigdata.edu.ddmath.view.LoadingPager;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


/**
 * 在线辅导
 * Created by Administrator on 2017/3/14.
 */

public class OnlineTutoringFragment extends Fragment implements View.OnClickListener, OnlineTutoringAdapter.TutorListener {

    private static final String TAG = "OnlineTutoringFragment";

    private Context mContext;
    private TutorModel mTutorModel = new TutorModel();

    private FrameLayout     mFlContent;
    private RelativeLayout  mRlTeacherList;
    private Button          mBtnSelectTutor;
    private LinearLayout    mLlPictureCount;
    private TextView        mTvPictureCount;
    private GridView        mGvTeacherList;
    private LoadingPager    mLoadingPager;
    private LinearLayout    mLlConnectTeacher;
    private CircleImageView mIvWaitingTeacherHead;
    private TextView        mTvWaitingTeacherName;
    private LinearLayout    mLlWaiting;
    private TextView        mTvWaitingEnterTime;
    private TextView        mTvWaitingQueueCount;
    private TextView        mTvWaitingTime;
    private LinearLayout    mLlTutoring;
    private Button          mBtnEnterTutor;
    private LinearLayout    mLlNoticeTips;

    private MyProgressDialog progressDialog;
    private int pageNum  = 1;
    private int pageSize = 20;
    private String mAccessToken;
    private String mStudentId;
    private String mTeacherId;
    private String mClassId;
    private int    mCoachId;

    private int                   pollingtime;
    private String                mTeacherName;
    private String                mTmage;
    private OnlineTutoringAdapter mOnlineTutoringAdapter;
    private List<OnlineTutoring> mTeacherList = new ArrayList<OnlineTutoring>();
    private boolean isTutorAppliedFail;
    private boolean teacherStateFail;
    private boolean isPolling;
    private PollingQueueTask mPollingQueueTask = new PollingQueueTask();
    private Handler          mHandler          = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //            mLoadingPager.showTarget();
            //            showWaitting();
            //            startPolling();
        }
    };
    private AutoQueryTask mAutoQueryTask;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("burning", "OnlineTutoringFragment onCreateView");
        View root = inflater.inflate(R.layout.view_online_tutoring, container, false);
        initView(root);
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        progressDialog = new MyProgressDialog(getContext());
        progressDialog.setMessage("加载中...");
        progressDialog.setCanceledOnTouchOutside(false);

        mFlContent = (FrameLayout) root.findViewById(R.id.fl_content);
        mRlTeacherList = (RelativeLayout) root.findViewById(R.id.rl_teacher_list);
        mBtnSelectTutor = (Button) root.findViewById(R.id.btn_select_tutor);
        mLlPictureCount = (LinearLayout) root.findViewById(R.id.ll_picture_count);
        mTvPictureCount = (TextView) root.findViewById(R.id.tv_picture_count);
        mGvTeacherList = (GridView) root.findViewById(R.id.gv_teacher_list);
        mLoadingPager = (LoadingPager) root.findViewById(R.id.loadingPager_online_tutoring);
        mLlConnectTeacher = (LinearLayout) root.findViewById(R.id.ll_connect_teacher);
        mIvWaitingTeacherHead = (CircleImageView) root.findViewById(R.id.iv_waiting_teacher_head);
        mTvWaitingTeacherName = (TextView) root.findViewById(R.id.tv_waiting_teacher_name);
        mLlWaiting = (LinearLayout) root.findViewById(R.id.ll_waiting);
        mTvWaitingEnterTime = (TextView) root.findViewById(R.id.tv_waiting_enter_time);
        mTvWaitingQueueCount = (TextView) root.findViewById(R.id.tv_waiting_queue_count);
        mTvWaitingTime = (TextView) root.findViewById(R.id.tv_waiting_time);
        mLlTutoring = (LinearLayout) root.findViewById(R.id.ll_tutoring);
        mBtnEnterTutor = (Button) root.findViewById(R.id.btn_enter_tutor);
        mLlNoticeTips = (LinearLayout) root.findViewById(R.id.ll_notice_tips);
        mRlTeacherList.setVisibility(View.INVISIBLE);
        mLlConnectTeacher.setVisibility(View.INVISIBLE);
        mLoadingPager.setTargetView(mFlContent);
        mLoadingPager.setEmptyText("未找到辅导老师");
        mLoadingPager.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断查询是否申请了辅导失败/获取辅导老师列失败
                mLoadingPager.showLoading();
                if (isTutorAppliedFail) {
                    isTutorApplied();
                } else {
                    queryTeacherState();
                }

            }
        });
        mBtnSelectTutor.setOnClickListener(this);
    }

    private void initData() {
        createLoginInfo();
    }

    //查询登录信息
    private void createLoginInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            mAccessToken = loginInfo.getAccessToken();
            Log.i(TAG, "mAccessToken=" + mAccessToken);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {

            } else {
                mClassId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                mStudentId = detailinfo.getStudentId();
                isTutorApplied();
                Log.i(TAG, "mClassId=" + mClassId + "mStudentId=" + mStudentId);
            }
        }
    }

    //查询是否申请了辅导
    public void isTutorApplied() {
        mTutorModel.isTutorApplied(mAccessToken, mStudentId, new RequestListener<TutorApplied>() {

            @Override
            public void onSuccess(TutorApplied vo) {
                Log.i(TAG, "isTutorApplied onSuccess");
                if (vo == null) {
                    isTutorAppliedFail = true;
                    mLoadingPager.showFault();
                    return;
                }
                isTutorAppliedFail = false;
                Log.i(TAG, "state=" + vo.getStates());
                //0->未申请，1->等待中，2->辅导中
                if (vo.getStates() == 0) {
                    queryTeacherState();
                    showTeacherList();
                } else {
                    mCoachId = vo.getCoachId();
                    SetHeadImage.setHeadIncomplete(mContext, mIvWaitingTeacherHead, vo.getImageUrl(), R.drawable.ico_teacher_head_normal);
                    mTvWaitingTeacherName.setText(vo.getTeacherName() + "老师");
                    String minute = DateUtils.getMinute(vo.getApplyTime());
                    mTvWaitingEnterTime.setText("您已于" + minute + "进入在线辅导队列");
                    mLoadingPager.showTarget();
                    if (vo.getStates() == 1) {
                        mTeacherId = vo.getTeacherId();
                        showWaitting();
                        queryTutorQueue();
                        startPolling();
                    } else {
                        showTutorting();
                    }
                }

            }

            @Override
            public void onFail(HttpResponse<TutorApplied> response, Exception ex) {
                Log.i(TAG, "isTutorApplied onFail");
                isTutorAppliedFail = true;
                mLoadingPager.showFault();
            }
        });
    }


    //获取辅导老师列表
    private void queryTeacherState() {
        mTutorModel.queryTeacherState(mAccessToken, mClassId, new RequestListener<List<OnlineTutoring>>() {

            @Override
            public void onSuccess(List<OnlineTutoring> res) {
                Log.i(TAG, "queryTeacherState onSuccess");
                if (res == null || res.size() == 0) {
                    teacherStateFail = true;
                    mLoadingPager.showEmpty();
                    return;
                }
                Log.i(TAG, "Teacher size=" + res.size());
                teacherStateFail = false;
                mTeacherList.clear();
                mTeacherList.addAll(res);
                if (mOnlineTutoringAdapter == null) {
                    mOnlineTutoringAdapter = new OnlineTutoringAdapter(mContext, mTeacherList, OnlineTutoringFragment.this);
                    mGvTeacherList.setAdapter(mOnlineTutoringAdapter);
                } else {
                    mOnlineTutoringAdapter.notifyDataSetChanged();
                }
                mLoadingPager.showTarget();
            }

            @Override
            public void onFail(HttpResponse<List<OnlineTutoring>> response, Exception ex) {
                Log.i(TAG, "queryTeacherState onFail");
                teacherStateFail = true;
                mLoadingPager.showFault();
            }
        });
    }

    //申请辅导
    private void applyapplyTutor(int time, final OnlineTutoring onlineTutoring) {
        String imageIds = DataUtils.getQuestionIds(GlobalData.getQustionMap());
        Log.i(TAG, "applyapplyTutor getTeacherId=" + onlineTutoring.getTeacherId());
        mTutorModel.applyTutor(mAccessToken, mStudentId, onlineTutoring.getTeacherId(), imageIds, time, new RequestListener<ApplyTutor>() {

            @Override
            public void onSuccess(ApplyTutor vo) {
                Log.i(TAG, "applyapplyTutor onSuccess");
                progressDialog.dismiss();
                showWaitting();
                startPolling();
                mCoachId = vo.getCoachId();
                SetHeadImage.setHeadIncomplete(mContext, mIvWaitingTeacherHead, onlineTutoring.getImageUrl(), R.drawable.ico_teacher_head_normal);
                mTvWaitingTeacherName.setText(onlineTutoring.getTeacherName() + "老师");
                String minute = DateUtils.getMinute(vo.getApplyTime());
                mTvWaitingEnterTime.setText("您已于" + minute + "进入在线辅导队列");
            }

            @Override
            public void onFail(HttpResponse<ApplyTutor> response, Exception ex) {
                Log.i(TAG, "applyapplyTutor onFail");
                progressDialog.dismiss();
                ToastUtils.showShort(mContext, R.string.server_error);
                retry();
            }
        });
    }

    private void retry() {

    }

    //开始轮询
    private void startPolling() {
        Log.i(TAG, "startPolling");
        if (mAutoQueryTask == null) {
            mAutoQueryTask = new AutoQueryTask();
        }
        mAutoQueryTask.start();
        queryTutorQueue();
    }

    // 控制是否重新跑流程 resume-在线辅导页面是否获取焦点
    public void restartRun(boolean resume) {
        Log.i(TAG, "restartRun resume" + resume);
        if (resume) {
            mLoadingPager.showLoading();
            isTutorApplied();
        } else {
            if (isPolling) {
                mAutoQueryTask.stop();
            }
        }
    }

   /* @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "OnlineTutoringFragment onResume() ");
        if (mAutoQueryTask != null) {
            restartRun(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "OnlineTutoringFragment onPause() ");
        if (mAutoQueryTask != null) {
            restartRun(false);
        }
    }*/

    /**
     * 轮询任务——是否轮到辅导
     */
    private class PollingQueueTask implements Runnable {

        @Override
        public void run() {
            queryTutorQueue();
        }
    }

    //查询是否轮到辅导
    private void queryTutorQueue() {
        Log.i(TAG, "queryTutorQueue");
        mTutorModel.isTutorTurn(mAccessToken, mStudentId, mTeacherId, new RequestListener<TutorTurn>() {

            @Override
            public void onSuccess(TutorTurn vo) {
                Log.i(TAG, "queryTutorQueue onSuccess");
                if (vo == null) {
                    return;
                }
                if (vo.isAccess()) {
                    showTutorDialog(vo.getCountdown());
                    mAutoQueryTask.stop();
                } else {
                    mTvWaitingQueueCount.setText("目前队列中还有：" + vo.getWaitingNumber() + "人");
                    mTvWaitingTime.setText("预计等待时间：" + vo.getWaitingTime() + "分");
                }
            }

            @Override
            public void onFail(HttpResponse<TutorTurn> response, Exception ex) {
                Log.i(TAG, "queryTutorQueue onFail");
            }
        });
    }

    //展示开始辅导Dialog——倒计时60S
    private void showTutorDialog(int countdown) {
        if (countdown <= 0) {
            showOvertimeDialog();
            return;
        }
        final TutorDialog tutorDialog = new TutorDialog(mContext, R.style.FullTransparentDialog);
        tutorDialog.setSecond(countdown);
        tutorDialog.setTutorDialogListener(new TutorDialog.TutorDialogListener() {
            @Override
            public void select(boolean click) {
                Log.i(TAG, "tutorDialog click=" + click);
                tutorDialog.dismiss();
                if (click) {
                    startTutor();
                } else {
                    showOvertimeDialog();
                }
            }
        });
        tutorDialog.show();
        tutorDialog.startCount();
    }

    //进入辅导
    private void startTutor() {
        Log.i(TAG, "startTutor() mCoachId=" + mCoachId);
        String remark = "remark——startTutor";
        mTutorModel.startTutor(mAccessToken, mCoachId, remark, new RequestListener<TutorState>() {

            @Override
            public void onSuccess(TutorState vo) {
                Log.i(TAG, "startTutor onSuccess");
                showTutorting();
                //// TODO: 2017/3/16 跳转到直播页面
                Intent intent = new Intent(getActivity(), TestRoomActivity.class);
                startActivityForResult(intent, 1);
            }

            @Override
            public void onFail(HttpResponse<TutorState> response, Exception ex) {
                Log.i(TAG, "startTutor onFail");
                ToastUtils.showShort(mContext, R.string.server_error);
                mLoadingPager.showLoading();
                isTutorApplied();
            }
        });
    }

    //展示超时Dialog
    private void showOvertimeDialog() {
        final TutorDialog overtimeDialog = new TutorDialog(mContext, R.style.FullTransparentDialog);
        overtimeDialog.setData("申请已超时", "确定");
        overtimeDialog.setTutorDialogListener(new TutorDialog.TutorDialogListener() {
            @Override
            public void select(boolean click) {
                Log.i(TAG, "showOvertimeDialog click=" + click);
                overtimeDialog.dismiss();
                //                ToastUtils.showShort(mContext, "返回列表页面");
                mLoadingPager.showLoading();
                isTutorApplied();
            }
        });
        overtimeDialog.show();
    }

    public class AutoQueryTask implements Runnable {
        /**
         * 开始滚动
         */
        public void start() {
            // 得到一个主线程的handler
            mHandler.removeCallbacks(this);
            mHandler.postDelayed(this, 10000);
            isPolling = true;
        }

        /**
         * 停止滚动
         */
        public void stop() {
            // 移除任务
            mHandler.removeCallbacks(this);
            isPolling = false;
        }

        @Override
        public void run() {
            // 递归
            start();
            queryTutorQueue();
        }
    }

    //展示老师列表
    private void showTeacherList() {
        mRlTeacherList.setVisibility(View.VISIBLE);
        mBtnSelectTutor.setVisibility(View.VISIBLE);
        mLlConnectTeacher.setVisibility(View.INVISIBLE);
        mLlNoticeTips.setVisibility(View.INVISIBLE);
    }

    //展示等待辅导界面
    private void showWaitting() {
        mRlTeacherList.setVisibility(View.INVISIBLE);
        mBtnSelectTutor.setVisibility(View.INVISIBLE);
        mLlConnectTeacher.setVisibility(View.VISIBLE);
        mLlWaiting.setVisibility(View.VISIBLE);
        mLlNoticeTips.setVisibility(View.VISIBLE);
        mLlTutoring.setVisibility(View.INVISIBLE);
    }

    //展示辅导中界面
    private void showTutorting() {
        mRlTeacherList.setVisibility(View.INVISIBLE);
        mBtnSelectTutor.setVisibility(View.INVISIBLE);
        mLlConnectTeacher.setVisibility(View.VISIBLE);
        mLlWaiting.setVisibility(View.INVISIBLE);
        mLlNoticeTips.setVisibility(View.INVISIBLE);
        mLlTutoring.setVisibility(View.VISIBLE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "requestCode= " + requestCode);
        if (resultCode == 0) {
            //从选择题目页面点击“返回按钮” 则清空临时题库
            HashMap<String, Boolean> qustionMap = GlobalData.getQustionMap();
            HashMap<String, Boolean> teamMap = GlobalData.getTeamMap();
            teamMap.clear();
            teamMap.putAll(qustionMap);
        } else {
            //从选择题目页面点击“完成选题” 则保存临时题库
            HashMap<String, Boolean> qustionMap = GlobalData.getQustionMap();
            HashMap<String, Boolean> teamMap = GlobalData.getTeamMap();
            qustionMap.clear();
            qustionMap.putAll(teamMap);
        }
        Set<String> set = GlobalData.getQustionMap().keySet();
        Log.i(TAG, "set.size()= " + set.size());
        if (set.size() > 0) {
            mTvPictureCount.setText("已选择" + set.size() + "张图片");
            mLlPictureCount.setVisibility(View.VISIBLE);
        } else {
            mLlPictureCount.setVisibility(View.INVISIBLE);
        }

        String questionIds = DataUtils.getQuestionIds(GlobalData.getQustionMap());
        Log.i(TAG, "questionIds= " + questionIds);

    }


    //选择在线辅导预约时长后 点击“发起在线辅导”
    @Override
    public void sendTutorClick(final OnlineTutoring onlineTutoring, int position) {
        SelectTimeDialog selectTimeDialog = new SelectTimeDialog(mContext);
        selectTimeDialog.setTimeSelectListener(new SelectTimeDialog.TimeSelectListener() {
            @Override
            public void select(int time) {
                progressDialog.show();
                applyapplyTutor(time, onlineTutoring);
                mTeacherId = onlineTutoring.getTeacherId();
                Log.i(TAG, "mTeacherId= " + onlineTutoring.getTeacherId() + " time= " + time);

            }
        });
        selectTimeDialog.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select_tutor: {
                Intent intent = new Intent(getActivity(), SelectQuestionsActivity.class);
                startActivityForResult(intent, 0);
            }
            break;
        }
    }

    public void setId(String accessToken, String classId, String studentId) {
        this.mAccessToken = accessToken;
        this.mClassId = classId;
        this.mStudentId = studentId;
    }

}
